package com.yupi.yuapigateway;

import com.yupi.yuapiclientsdk.utils.SignUtils;
import com.yupi.yuapicommon.model.entity.InterfaceInfo;
import com.yupi.yuapicommon.model.entity.User;
import com.yupi.yuapicommon.service.InnerInterfaceInfoService;
import com.yupi.yuapicommon.service.InnerUserInterfaceInfoService;
import com.yupi.yuapicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    private static final String INTERFACE_HOST = "http://localhost:8123";

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        // 1. 用户发送请求到API网关
        // 2. 请求日志
        ServerHttpRequest request = exchange.getRequest();
        log.info("请求的唯一标识：" + request.getId());
        String path = INTERFACE_HOST + request.getPath().value();
        String method = request.getMethod().toString();
        log.info("请求的路径：" + path);
        log.info("请求的method：" + method);
        log.info("请求的参数：" + request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求来源地址：" + sourceAddress);
        log.info("请求来源地址：" + request.getRemoteAddress());
        // 3. 访问控制：黑白名单
        ServerHttpResponse response = exchange.getResponse();
        if (!IP_WHITE_LIST.contains(sourceAddress)) {
            return handleNoAuth(response);
        }
        // 4. 用户鉴权（判断ak, sk是否合法）
        //4.1.从请求头中拿到5个参数值做校验，比如accessKey,nonce,bodyMD5,timestamp
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String body = headers.getFirst("body");

        //4.2.权限校验，比如accessKey是否存在，是否过期，是否被禁用.  实际上是从数据库中插叙是否已分配给用户
        User invokeUser = null;
        try {
            // 调用内部服务，根据访问秘钥获取用户信息
            invokeUser = innerUserService.getInvokeUser(accessKey);
        } catch (Exception e) {
            // 捕获异常，记录日志
            log.error("getInvokeUser error",e);
        }
        if (invokeUser == null) {
            return handleNoAuth(response);
        }

        //4.3.随机数校验
        if (nonce == null || Long.parseLong(nonce) > 10000) {
            return handleNoAuth(response);
        }

        //4.4.时间和当前时间不超过5分钟
        if (System.currentTimeMillis() / 1000 - Long.parseLong(timestamp) > 60 * 5) {
            return handleNoAuth(response);
        }

        //4.5.签名校验, 实际上是从数据库中查询出secretKey，然后进行签名校验
        String secretKey = invokeUser.getSecretKey(); //从用户信息中获取秘钥
        String serveSign = SignUtils.genSign(body, secretKey); // 使用获取的秘钥对请求体进行签名
        if (sign == null || !sign.equals(serveSign)) {
            // 若签名为空 或签名不一致
            return handleNoAuth(response);
        }


        // 5. 请求的模拟接口是否存在(从数据库中查询模拟接口是否存在)
        InterfaceInfo interfaceInfo = null;
        try {
            // 尝试从内部接口信息服务获取指定路径和方法的接口信息
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path, method);
        } catch (Exception e) {
            log.error("getInterfaceInfo error", e);
        }
        if (interfaceInfo == null) {
            return handleNoAuth(response);
        }

        /*// 6. 请求转发，调用模拟接口
        Mono<Void> filter = chain.filter(exchange);

        // 7. 调用成功后，设置响应日志
        log.info("响应：" + response.getStatusCode());

        // TODO 8. 调用成功，接口调用次数 + 1
        if (response.getStatusCode() == HttpStatus.OK) {

        } else {
            // 9. 调用失败，返回一个规范的错误码
            return handleInvokeError(response);
        }

        log.info("custom global filter");
        return filter;*/

        return handleResponse(exchange, chain,interfaceInfo.getId(), invokeUser.getId());
    }

    @Override
    public int getOrder() {
        return -1;
    }

    public Mono<Void> handleNoAuth(ServerHttpResponse response) {
        //设置响应状态码为403 Forbidden（禁止访问）
        response.setStatusCode(HttpStatus.FORBIDDEN);
        // 返回处理完成响应
        return response.setComplete();
    }

    public Mono<Void> handleInvokeError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }

    /**
     * 处理响应
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceId, long userId) {
        try {
            // 获取原始的响应对象
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 获取数据缓冲工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            HttpStatus statusCode = originalResponse.getStatusCode();

            // 判断状态码是否为200 OK（疑问：还未调用，为啥可以拿到状态码？）
            if(statusCode == HttpStatus.OK){
                // 创建一个装饰后的响应对象（开始穿装备，增强能力）
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    // 重写writeWith方法，用于处理响应体数据
                    // 这个方法作用：当模拟方法调用完成后，等它返回结果
                    // 调用writeWith方法，可根据响应结果做一些自己的处理
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            //返回一个处理后的响应体
                            // 可理解为在拼接字符串，把缓存区的数据取出来 进行字符串拼接
                            return super.writeWith(fluxBody.map(dataBuffer -> {

                                // 8. 调用成功，接口调用次数 + 1
                                try {
                                    // 调用内部用户接口信息服务，记录接口调用次数
                                    innerUserInterfaceInfoService.invokeCount(interfaceId, userId);
                                } catch (Exception e) {
                                    log.error("invokeCount error", e);
                                }

                                //读取影响体内容并转换为字符串数组
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);

                                //打印日志
                                log.info("响应结果：" + sb2.toString());//响应结果：POST 用户名字是:yuapi
                                //将处理后的内容重新包装成DataBuffer并返回
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                //对于 200 OK的请求，将装饰后的响应对象传递给下一个过滤器链，并继续处理（设置response对象为装饰过的）
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            // 对于非200 OK的请求，直接返回，进行降级处理
            return chain.filter(exchange);//降级处理返回数据
        }catch (Exception e){
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }

    }
}

